package com.xspace.android.xafcommon.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cn.wt.wtutils.AppManager;
import com.xspace.android.xafcommon.R;
import com.xspace.android.xafcommon.been.PageBean;
import com.xspace.android.xafcommon.been.PageCommonBean;
import com.xspace.android.xafcommon.util.ClassUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.view.ProgressLoading;
import com.xspace.android.xafcommon.view.dialog.DialogControl;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import java.util.Map;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * liuchen 创建于 2016/10/13.
 */
public class BaseActivity extends AppCompatActivity implements DialogControl {
    private ProgressLoading mProgressLoading;
    protected ProgressDialog mProgress;
    private boolean progressShow;
    protected Context mContext;
    protected PageBean mPagebean = new PageBean();
    protected PageCommonBean mPageCommonbean = new PageCommonBean();
    protected LayoutInflater mInflater;
    protected InputMethodManager inputManager;
    private final CompositeSubscription mAllSubscription = new CompositeSubscription();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.d("onCreate");
        // 判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
//        StatusBarUtils.setWindowStatusBarColor(this, ResourceUtils.getColor(R.color.theme_color));
        super.onCreate(savedInstanceState);
//        ActionBar bar = getSupportActionBar();
//        LogUtil.d("bar == null?" + (bar == null));
        AppManager.getAppManager().addActivity(this);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        }
        mContext = this;
        mInflater = LayoutInflater.from(mContext);
        mProgress = DialogHelp.getWaitDialog(mContext, getString(R.string.loading));
        mProgress.setCancelable(true);
        mProgress.setCanceledOnTouchOutside(false);

        getIntentData();
        initView();
        initFindViewById();
        initData();
        initEvent();

    }

    protected void hideSoftKeyboard() {
        if (inputManager == null)
            inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void registerSubscription(Subscription subscription) {
        mAllSubscription.add(subscription);
    }

    protected void unregisterSubscription(Subscription subscription) {
        mAllSubscription.remove(subscription);
    }

    @SuppressWarnings("unchecked")
    public <T> T $(int id) {
        return (T) this.findViewById(id);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    protected boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    protected void clearSubscription() {
        LogUtil.d(" 是否还有Subscriptions " + mAllSubscription.hasSubscriptions() + " clear");
        mAllSubscription.clear();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ClassUtil.getOtherMethod(ClassUtil.getMethod(ClassUtil.NOTIFIER_CLASS, "getInstance"), "reset");
//        Notifier.getInstance().reset();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);

        clearSubscription();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    protected void initView() {
        LogUtil.d("initView");
    }

    protected void initData() {
        LogUtil.d("initData");
    }

    protected void initFindViewById() {
        LogUtil.d("initFindViewById");
    }

    protected void getIntentData() {
        LogUtil.d("getIntentData");
    }

    protected void initEvent() {
        LogUtil.d("initEvent");
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    public void onEventMainThread(Map<String, Object> inParam) {
    }

    public ProgressLoading getProgressLoading() {
        return mProgressLoading;
    }

    public void showProgressLoading(String message) {
        if (mProgressLoading == null) {
            mProgressLoading = new ProgressLoading(mContext, R.style.ProgressLoadingTheme);
            mProgressLoading.setCanceledOnTouchOutside(true);
            mProgressLoading.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    progressShow = false;
                }
            });
        }
        if (!TextUtils.isEmpty(message)) {
            mProgressLoading.setMessage(message);
        } else {
            mProgressLoading.setMessage(null);
        }
        progressShow = true;
        mProgressLoading.show();
    }

    protected ProgressDialog getmProgressDialog() {
        return mProgress;
    }

    public void showProgress(String text) {
        if (mProgress != null && !mProgress.isShowing()) {
            if (!TextUtils.isEmpty(text)) {
                setMessage(text);
            }
            mProgress.show();
        }
    }

    /**
     * @param @param id
     * @return void
     * @throws
     * @Description: 设置等待文本内容 int 类型
     */
    private void setMessage(int id) {
        mProgress.setMessage(getString(id));
    }

    /**
     * @param @param msg
     * @return void
     * @throws
     * @Description: 设置等待文本内容 String
     */
    private void setMessage(String msg) {
        mProgress.setMessage(msg);
    }

    /**
     * 不显示圈圈
     */
    private void dismissProgress() {
        if (mProgress != null && mProgress.isShowing()) {
            mProgress.dismiss();
        }
    }

    public boolean isProgressShow() {
        return progressShow;
    }

    public void dismissProgressLoading() {
        if (mProgressLoading != null && !isFinishing()) {
            progressShow = false;
            mProgressLoading.dismiss();
        }
    }

    public void hideSoftInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    private void hideKeyboard(IBinder token) {
        LogUtil.d("hideKeyboard..........");
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void showSoftInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (!imm.isActive()) {
            imm.showSoftInput(getCurrentFocus(), InputMethodManager.SHOW_FORCED);
        }
    }

    @Override
    public void hideWaitDialog() {
        dismissProgress();
    }

    @Override
    public void showWaitDialog() {
        showProgress("");
    }

    @Override
    public void showWaitDialog(int resourcesId) {
        showProgress(getString(resourcesId));
    }

    @Override
    public void showWaitDialog(String text) {
        showProgress(text);
    }
}
